import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { printApi } from '../services/api';

/**
 * 打印记录相关逻辑的Hook
 */
export function usePrintRecords() {
  // 响应式数据
  const records = ref([]);
  const loading = ref(false);
  const page = ref(1);
  const limit = ref(10);
  const total = ref(0);
  const pages = ref(0);
  const keyword = ref('');

  // 加载打印记录
  const loadRecords = async () => {
    loading.value = true;
    try {
      const result = await printApi.getPrintRecords({
        page: page.value,
        limit: limit.value,
        keyword: keyword.value
      });
      records.value = result.records || [];
      
      total.value = result.total || 0;
      pages.value = result.pages || 0;
    } catch (error) {
      console.error('获取打印记录失败:', error);
      ElMessage.error('获取打印记录失败，请稍后重试');
      records.value = []; // 出错时确保列表为空
    } finally {
      loading.value = false;
    }
  };

  // 搜索记录
  const searchRecords = (searchKeyword) => {
    keyword.value = searchKeyword;
    page.value = 1;
    loadRecords();
  };

  // 重置搜索
  const resetSearch = () => {
    keyword.value = '';
    page.value = 1;
    loadRecords();
  };

  // 刷新打印记录
  const refreshRecords = () => {
    page.value = 1;
    loadRecords();
  };

  // 处理每页条数变化
  const handleSizeChange = (newSize) => {
    limit.value = newSize;
    page.value = 1;
    loadRecords();
  };

  // 切换页码
  const changePage = (newPage) => {
    page.value = newPage;
    loadRecords();
  };

  // 格式化日期时间
  const formatDateTime = (dateTime) => {
    if (!dateTime) return '-';
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) return '-';
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  };

  // 初始加载数据
  loadRecords();

  // 返回需要在组件中使用的响应式数据和方法
  return {
    records,
    loading,
    page,
    limit,
    total,
    pages,
    keyword,
    loadRecords,
    refreshRecords,
    handleSizeChange,
    changePage,
    formatDateTime,
    searchRecords,
    resetSearch
  };
}